import WPT from 'wpt';

function isWebpSupportted(imageDate) {
    if (Number.isNaN(imageDate)) {
        return false;
    }

    return Boolean(window.Modernizr && window.Modernizr.webp);
}

const { hostname } = window.location;

export function getWebpSrc(src) {
    if (!src || hostname !== 'w.weipaitang.com') {
        return src;
    }

    const [, year, month, day] = src.match(/\/img\/(\d{4})(\d{2})(\d{2})/) || [];

    if (day) {
        const imageDate = new Date([year, month, day].join('-'));

        // ios app 添加 webp支持标识
        if (
            WPT.os.ios
            && WPT.os.wpt
            && window.navigator.userAgent.match(/webp\/support/i) // 如果支持此特性，App会在UA中添加webp/support标识
            && (WPT.isDeveloper || WPT.os.wptAppVersion >= 351)
        ) {
            return src
                .replace(/^(https?:)?\/{2}/, 'wptwebp://')
                .replace('/img/', '/imgwebp/');
        }

        if (isWebpSupportted(imageDate)) {
            return src.replace('/img/', '/imgwebp/');
        }
    }

    return src;
}

export default getWebpSrc;
